package org.jeecg.modules.yusuan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.yusuan.entity.CaiwuBiaozhun;
import org.jeecg.modules.yusuan.entity.CaiwuLiuyong;
import org.jeecg.modules.yusuan.entity.CaiwuNz;
import org.jeecg.modules.yusuan.entity.CaiwuXiangmu;
import org.jeecg.modules.yusuan.service.ICaiwuNzService;
import org.jeecg.modules.yusuan.service.ICaiwuXiangmuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
* @Author: jeecg-boot
* @Date:   2020-06-15
* @Version: V1.0
*/
@RestController
@RequestMapping("/yusuan/xiangmu")
@Slf4j
public class CaiwuXiangmuController extends JeecgController<CaiwuXiangmu, ICaiwuXiangmuService> {
    @Autowired
    private ICaiwuNzService caiwuNzService;
   @Autowired
   private ICaiwuXiangmuService caiwuXiangmuService;
   @Autowired
   private ISysDepartService sysDepartService;

   @PostMapping("/addlist")
   public Result<?> addList(@RequestBody List<CaiwuXiangmu> list){
       this.caiwuXiangmuService.saveOrUpdateBatch(list);
       return Result.ok("操作成功");
   }

    /**
     * 加载所有数据
     */
    @RequestMapping(value = "/loadData", method = RequestMethod.GET)
    public Result<List<CaiwuXiangmu>> loadTreeRoot(@RequestParam(name = "type")String type
            ,@RequestParam( value = "deptId",required = false)String deptId
            ,@RequestParam(name="pid") String pid
            ,@RequestParam(value = "effective",required = false) Integer effective) {
        if(StringUtils.isBlank(deptId)){
            String orgCode = ((LoginUser) SecurityUtils.getSubject().getPrincipal()).getOrgCode();
            deptId = this.sysDepartService.getOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getOrgCode,orgCode)).getId();
        }
        if(null == effective)
            effective = 1;
        Integer version = this.caiwuXiangmuService.getMaxVersion(effective,deptId);
        String deptCode = this.sysDepartService.getById(deptId).getOrgCode();
        Result<List<CaiwuXiangmu>> result = new Result<List<CaiwuXiangmu>>();
        try {
            Map<String,CaiwuXiangmu> allData = new HashMap<>();
            List<CaiwuXiangmu> leafList = new ArrayList<>();
            Set<CaiwuXiangmu> leafSet = new HashSet<>(); //A01
            List<CaiwuXiangmu> ls = null;
            if(StringUtils.equals(type,"zhibiao")) {
                ls = this.caiwuXiangmuService.zhibiaolistData(deptId, deptCode, pid,effective,version);
            }else if(StringUtils.equals(type,"shenqing")){
                ls = this.caiwuXiangmuService.listData(deptId, deptCode, pid,effective,version);
            }else if(StringUtils.equals(type,"shenpi")){
                ls = this.caiwuXiangmuService.listData(deptId, deptCode, pid,effective,version);
            }
            loadDataChildren(leafList,allData,type,deptId,deptCode,ls,effective,version);

            if(!CollectionUtils.isEmpty(leafList)){
                leafList.forEach(item->{
                    String xiafashu = item.getXiafashu();
                    String orgCode = item.getSysOrgCode();

                    if(!StringUtils.equalsIgnoreCase(orgCode,"A01")){
                        xiafashu = allData.get(item.getParentId()).getXiafashu();
                        leafSet.add(allData.get(item.getParentId()));
                    }else{
                        leafSet.add(item);
                    }
                    xiafashu = null == xiafashu?"0":xiafashu;
                    item.setMaxNum(xiafashu);
                    if(Double.parseDouble(xiafashu)>0){
                        item.setDisplay(true);
                    }

                });
                leafSet.forEach(item->{
                    String xiafashu = item.getXiafashu();
                    xiafashu = null == xiafashu?"0":xiafashu;
                    item.setMaxNum(xiafashu);
                    if(Double.parseDouble(xiafashu)>0){
                        item.setDisplay(true);
                        iterParent(allData,item,item);
                    }
                });
            }
            CaiwuXiangmu total = new CaiwuXiangmu();
            BeanUtils.copyProperties(ls.get(0),total);
            total.setIsLeaf(true);
            total.setChildren(null);
            total.setCategoryId("0");
            total.setCategoryName("合计");
            ls.add(0,total);
            result.setResult(ls);
            result.setSuccess(true);

            if(StringUtils.equals(type,"shenpi") && StringUtils.isNotBlank(total.getShenheshu()) && Double.parseDouble(total.getShenheshu())>0){
                List<CaiwuNz> nzList = caiwuNzService.list(new LambdaQueryWrapper<CaiwuNz>().eq(CaiwuNz::getDeptId,deptId).eq(CaiwuNz::getJingfeiType,"xiangmu"));
                if(CollectionUtils.isEmpty(nzList)){
                    CaiwuNz caiwuNz = new CaiwuNz();
                    caiwuNz.setXiafashu(total.getXiafashu());
                    caiwuNz.setShenqingshu(total.getShenqingshu());
                    caiwuNz.setShenheshu(total.getShenheshu());
                    caiwuNz.setZengjian(total.getZengjian());
                    caiwuNz.setDeptId(deptId);
                    caiwuNz.setJingfeiType("xiangmu");
                    caiwuNzService.save(caiwuNz);
                }else {
                    CaiwuNz caiwuNz = nzList.get(0);
                    if(StringUtils.isBlank(caiwuNz.getProcessInstanceId())){
                        caiwuNz.setXiafashu(total.getXiafashu());
                        caiwuNz.setShenqingshu(total.getShenqingshu());
                        caiwuNz.setShenheshu(total.getShenheshu());
                        caiwuNz.setZengjian(total.getZengjian());
                        caiwuNzService.updateById(caiwuNz);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setSuccess(false);
        }
        result.setMessage(deptId);
        return result;
    }

    private void iterParent(Map<String,CaiwuXiangmu> allData,CaiwuXiangmu biaozhun,CaiwuXiangmu leafItem){
        String categoryId = biaozhun.getParentId();
        CaiwuXiangmu parent =allData.get(categoryId);
        if(null == parent){
            return;
        }
        parent.setDisplay(true);
        if(!StringUtils.equals(parent.getId(),"1270528547133616130")){
            if(StringUtils.equalsIgnoreCase(biaozhun.getSysOrgCode(),"A01")) {
                String xiafashu = parent.getXiafashu();
                xiafashu = null == xiafashu ? "0" : xiafashu;
                String xfs = leafItem.getXiafashu();
                xfs = null == xfs ? "0" : xfs;
                parent.setXiafashu((Double.parseDouble(xiafashu) + Double.parseDouble(xfs)) + "");

                String shenqingshu = parent.getShenqingshu();
                shenqingshu = null == shenqingshu ? "0" : shenqingshu;
                String sqs = leafItem.getShenqingshu();
                sqs = null == sqs ? "0" : sqs;
                parent.setShenqingshu((Double.parseDouble(shenqingshu) + Double.parseDouble(sqs)) + "");

                String shenheshu = parent.getShenheshu();
                shenheshu = null == shenheshu ? "0" : shenheshu;
                String shs = leafItem.getShenheshu();
                shs = null == shs ? "0" : shs;
                parent.setShenheshu((Double.parseDouble(shenheshu) + Double.parseDouble(shs)) + "");

                String zengjian = parent.getZengjian();
                zengjian = null == zengjian?"0":zengjian;
                String zj = leafItem.getZengjian();
                zj = null == zj?"0":zj;
                parent.setZengjian((Double.parseDouble(zengjian) + Double.parseDouble(zj)) + "");
            }
            iterParent(allData,parent,leafItem);
        }
    }

    /**
     * 递归求子节点 同步加载用到
     */
    private void loadDataChildren(List<CaiwuXiangmu> leafList,Map<String,CaiwuXiangmu> allData,String type,String deptId,String deptCode,List<CaiwuXiangmu> ls,Integer effective,Integer version) {
        for (CaiwuXiangmu tsm : ls) {
            allData.put(tsm.getTreeId(),tsm);
            List<CaiwuXiangmu> temp = null;
            if(StringUtils.equals(type,"zhibiao")) {
                temp = this.caiwuXiangmuService.zhibiaolistData(deptId, deptCode, tsm.getTreeId(),effective,version);
            }else if(StringUtils.equals(type,"shenqing")){
                temp = this.caiwuXiangmuService.listData(deptId, deptCode, tsm.getTreeId(),effective,version);
            }else if(StringUtils.equals(type,"shenpi")){
                temp = this.caiwuXiangmuService.listData(deptId, deptCode, tsm.getTreeId(),effective,version);
            }
            if(temp!=null && temp.size()>0) {
                tsm.setChildren(temp);
                loadDataChildren(leafList,allData,type,deptId,deptCode,temp,effective,version);
            }else{
                leafList.add(tsm);
            }
        }
    }
}
